from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from products.models import Product
from products.serializers import ProductSerializer
from .models import Order
from .serializers import OrderSerializer
import jwt
from django.conf import settings

# Create your views here.
'''
(5)封下单接口：POST 
①参数说明：product_id，用户id，商品数量，商品价格。 
②逻辑要求： 
a)product_id，用户id需要使用对应关联的数据，表无关联不给分
b)多个商品时，表中的总价字段，后端自己计算
c)表中订单状态的状态默认为“待支付”
'''

class OrderCreateView(APIView):
    def post(self,request):

        # 获取token是否存在
        token = request.headers.get('Authorization')
        if not token:
            return Response({"message": "token为空时不允许添加商品"}, status=status.HTTP_401_UNAUTHORIZED)
        # 解析token
        playload = jwt.decode(token, settings.SECRET_KEY, algorithms='HS256')
        user = playload['user_name']
        # 准备订单数据
        order_data = {
            'user':user,
            'item':[]
        }

        # 处理订单数据
        for item in request.data['item']:
            # 获取商品数据
            product = Product.objects.get(id=item['product_id'])

        # 添加订单
        order_data['item'].append({
            'product_id':product.id,
            'product_price':product.price,
            'quantity':item['quantity'],
            'total_price':product.price*item['quantity']
        })

        # 创建订单数据
        serializer = OrderSerializer(data=order_data)
        serializer.is_valid(raise_exception=True)
        order = serializer.save()

        return Response({
            'message': '下单成功',
            'data':{
                'order_id':order.id,
                'total_amount':order.amount,
                'order_status':order.order_status
            }
        },status=status.HTTP_201_CREATED)